package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author 虎哥
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "user:register:phone:";

    @Override
    public Boolean isInfoExists(String data, Integer type) {
        // 健壮性判断
        if (type != 1 && type != 2) {
            // 数据有误
            throw new LyException(400, "请求参数有误！");
        }

        // select count(*) from tb_user where username = ""
        Integer count = query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count();
        // 判断是否存在
        return count > 0;
    }

    @Override
    public void sendVerifyCode(String phone) {
        // 1.接收前端请求参数中的手机号，并验证
        if (!RegexUtils.isPhone(phone)) {
            // 手机号错误
            throw new LyException(400, "手机号格式错误！");
        }

        // 2.生成随机验证码
        String code = RandomStringUtils.randomNumeric(6);

        // 3.保存验证码到redis
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        // 4.利用AmqpTemplate，发送消息到ly-sms
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Override
    public void register(User user, String code) {
        // 1.校验验证码是否正确
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(cacheCode, code)) {
            // 验证码错误
            throw new LyException(400, "验证码错误!");
        }
        // 3.密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 4.把用户写入数据库
        save(user);
    }

    @Override
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        // 根据用户名查询用户
        User user = query().eq("username", username).one();
        // 判断是否存在
        if (user == null) {
            // 用户不存在，用户名是错误的
            throw new LyException(400, "用户名或密码错误！");
        }
        // 用户名正确的，校验密码
        String encodedPassword = user.getPassword();
        if(!passwordEncoder.matches(password, encodedPassword)){
            // 密码错误
            throw new LyException(400, "用户名或密码错误！");
        }
        // 返回用户
        return new UserDTO(user);
    }
}